package cn.itcast.hotel.listener;

import cn.itcast.hotel.constant.MqConstants;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author liudo
 * @version 1.0
 * @project hotel-demo
 * @date 2023/10/28 17:47:27
 */
@Slf4j
@Component
public class MqListener {

    private static final String HOTEL = "hotel";
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private HotelMapper hotelMapper;

    @RabbitListener(queues = MqConstants.HOTEL_DELETE_QUEUE)
    public void deleteListener(String hotelId) {
        try {
            DeleteRequest request = new DeleteRequest(HOTEL, hotelId);
            restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    @RabbitListener(queues = MqConstants.HOTEL_INSERT_QUEUE)
    public void insertOrUpdateListener(String hotelId) {
        try {
            IndexRequest indexRequest = new IndexRequest(HOTEL).id(hotelId);
            Hotel hotel = hotelMapper.selectById(hotelId);
            HotelDoc hotelDoc = new HotelDoc(hotel);
            indexRequest.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
